/*
 * Copyright (C), 2002-2016, 上海亦寻信息技术有限公司
 * FileName: SubscribeServiceImp.java
 * Author:   linyao
 * Date:     2016-7-8 下午2:42:24
 * Description: //模块目的、功能描述      
 * History: //修改记录
 * <author>      <time>      <version>    <desc>
 * 修改人姓名             修改时间            版本号                  描述
 */
package com.emm.yixun.website.service.customer;

import java.util.ArrayList;
import java.util.List;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.emm.yixun.common.model.*;
import com.emm.yixun.common.model.dto.*;
import com.emm.yixun.common.model.enums.*;
import com.emm.yixun.system.service.BaseCodeTypeServiceFacade;
import com.emm.yixun.system.service.BaseCodeValueServiceFacade;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.emm.yixun.common.exception.XFUNExceptionCode;
import com.emm.yixun.common.response.Response;
import com.emm.yixun.common.response.ResponseList;
import com.emm.yixun.common.utils.DateStyle;
import com.emm.yixun.common.utils.DateUtils;
import com.emm.yixun.customer.service.CallCustomerServiceFacade;
import com.emm.yixun.customer.service.CustomerServiceFacade;
import com.emm.yixun.customer.service.DistributionServiceFacade;
import com.emm.yixun.customer.service.FollowServiceFacade;
import com.emm.yixun.estate.service.ProjectServiceFacade;
import com.emm.yixun.system.service.UserServiceFacade;
import com.emm.yixun.website.common.utils.security.ShiroUtil;

/**
 * 〈一句话功能简述〉 〈功能详细描述〉
 * 
 * @author linyao
 * @see [相关类/方法]（可选）
 * @since [产品/模块版本] （可选）
 */
@Service
public class DistributionServiceImp implements DistributionService {
	@Autowired
	private CallCustomerServiceFacade callCustomerServiceFacade;
	@Autowired 
	private CustomerServiceFacade customerServiceFacade;
	@Autowired
	private DistributionServiceFacade distributionServiceFacade;
	@Autowired
	private ProjectServiceFacade projectServiceFacade;
	@Autowired
	private FollowServiceFacade followServiceFacade;
	@Autowired
	private UserServiceFacade userServiceFacade;
	@Autowired
	private BaseCodeValueServiceFacade baseCodeValueServiceFacade;
	@Autowired
	private BaseCodeTypeServiceFacade baseCodeTypeServiceFacade;

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.emm.yixun.website.service.customer.SubscribeService#getSubscribeList(com.emm.yixun.common.model.dto.SubscribeDto
	 * , java.lang.Integer, java.lang.Integer)
	 */
	@Override
	public Response<CustomerDto> addCustomer(String ids, Project project, String customerId){
		Response<CustomerDto> resCus = new Response<CustomerDto>();
		User user=ShiroUtil.getCurrentUser();
		
		CallCustomerDto dto = new CallCustomerDto();
		dto.setSql(ids);
		dto.setStatus("3"); //已转客
		dto.setAssignedType("0"); //未分配
		ResponseList<CallCustomer> resCall = callCustomerServiceFacade.setValueGetListDto(dto);
		if(resCall.isSuccess()){

			BaseCodeTypeDto bctDto = new BaseCodeTypeDto();
			bctDto.setMerchantId(project.getMerchantId());
			bctDto.setProjectId(project.getId());
			bctDto.setTypeValue(BaseCodeTypeConvertEnum.TYPE_ONE.getDes());
			ResponseList<BaseCodeType> bctResList = baseCodeTypeServiceFacade.findByDto(bctDto);
			Long typeId = null;
			if(bctResList.isSuccess()){
				List<BaseCodeType> bctList = bctResList.getEntity();
				if(null != bctList && bctList.size() > 0){
					typeId = bctList.get(0).getId();
				}
			}
			Long valueId = null;
			if(null != typeId){
				BaseCodeValueDto bcvDto = new BaseCodeValueDto();
				bcvDto.setCodeName("渠道转客");
				bcvDto.setProjectId(project.getId());
				bcvDto.setTypeId(typeId);
				ResponseList<BaseCodeValue> bcvResList = baseCodeValueServiceFacade.findByDto(bcvDto);
				if(bcvResList.isSuccess() && bcvResList.getEntity().size() > 0){
					List<BaseCodeValue> bcvList = bcvResList.getEntity();
					for(BaseCodeValue bcv: bcvList){
						if("初始化".equals(bcv.getRemark())){
							valueId = bcv.getId();
							break;
						}
					}
				}
			}
			List<CallCustomer> callList = resCall.getEntity();
			for(int i = 0; i < callList.size(); i++){
				CallCustomer call = (CallCustomer)callList.get(i);
				//新增客户信息
				resCus = saveCustomer(call, project, customerId, user, valueId);
				if(!resCus.isSuccess()){
					return resCus;
				}
				//新增分配记录
				Response<DistributionDto> resDis = saveDistribution(call, resCus.getEntity(), customerId, user);
				if(!resDis.isSuccess()){
					resCus.setSuccess(false);
					resCus.setErrorCode("9999");
					resCus.setResultMessage("保存客户分配记录失败");
					return resCus;
				}
				//新增分配记录
				Response<FollowDto> resFollow = saveFollow(call, resCus.getEntity(), customerId, user);
				if(!resFollow.isSuccess()){
					resCus.setSuccess(false);
					resCus.setErrorCode("9999");
					resCus.setResultMessage("保存跟进记录录失败");
					return resCus;
				}
				
				//修改call客状态为已分配
				CallCustomerDto callDto = new CallCustomerDto();
				callDto.setId(call.getId());
				callDto.setAssignedType("1"); //已分配
				callDto.setUpdateUserId(user.getId());
				callCustomerServiceFacade.updateByPrimaryKey(callDto, true);
			}
		}
		
		return resCus;
	}
	//新增客户信息
	public Response<CustomerDto> saveCustomer(CallCustomer dto, Project project, String customerId, User user, Long valueId){
		Response<CustomerDto> resCus = new Response<CustomerDto>();
		CustomerDto cusDto = new CustomerDto();
    	cusDto.setCustomerPhone(dto.getPhone());
		cusDto.setMerchantId(project.getMerchantId());
		cusDto.setProjectId(project.getId());
		cusDto.setDelFlag("0");
		//查询是否已存在
		ResponseList<Customer> resList = customerServiceFacade.selectCustomerPhoneByListPC(cusDto);
		if(resList.isSuccess()){
			if(resList.getEntity() != null){
				resCus.setSuccess(false);
				resCus.setErrorCode(XFUNExceptionCode.USER_CUSTOMERPHONEEXIST.getCode());
				resCus.setResultMessage("客户已存在");
				return resCus;
			}
		}

		Long ftContactWay = null;
		BaseCodeTypeDto bctDto = new BaseCodeTypeDto();
		bctDto.setMerchantId(project.getMerchantId());
		bctDto.setProjectId(project.getId());
		bctDto.setTypeValue(BaseCodeTypeConvertEnum.TYPE_ELEVEN.getDes());
		ResponseList<BaseCodeType> bctResList = baseCodeTypeServiceFacade.findByDto(bctDto);
		Long typeId = null;
		if(bctResList.isSuccess()){
			List<BaseCodeType> bctList = bctResList.getEntity();
			if(null != bctList && bctList.size() > 0){
				typeId = bctList.get(0).getId();
			}
		}
		if(null != typeId){
			BaseCodeValueDto bcvDto = new BaseCodeValueDto();
			bcvDto.setCodeName("来访");
			bcvDto.setProjectId(project.getId());
			bcvDto.setTypeId(typeId);
			ResponseList<BaseCodeValue> bcvResList = baseCodeValueServiceFacade.findByDto(bcvDto);
			if(bcvResList.isSuccess() && bcvResList.getEntity().size() > 0){
				List<BaseCodeValue> bcvList = bcvResList.getEntity();
				for(BaseCodeValue bcv: bcvList){
					if("初始化".equals(bcv.getRemark())){
						ftContactWay = bcv.getId();
						break;
					}
				}
			}
		}

		//查询经纪人userCode
		Response<User> resUser = userServiceFacade.findById(Long.parseLong(customerId));
		
    	cusDto.setCustomerName(dto.getUserName());
		cusDto.setProjectId(project.getId());
		cusDto.setProjectCode(project.getProjectCode());
		cusDto.setUserCode(resUser.getEntity().getUserCode()); //经纪人
		cusDto.setAccessCode(project.getAccessCode());
		cusDto.setProcessStatus(ProcessStatusEnum.YES.getNo());
		cusDto.setCustomerOrigin(CustomerOriginEnum.CALLKE_11.getNo());
		cusDto.setCreateUserId(user.getId()); //分配人
		cusDto.setOrgStores(dto.getOrgStores());
		if(StringUtils.isNotEmpty(dto.getRecommendedChannelId()) && null != valueId){
			cusDto.setInformedWay(String.valueOf(valueId));
			cusDto.setIntentionLevel(IntentionLevelEnum.D.getNo());
			cusDto.setCustomerStatus(CustomerStatusEnum.VISIT.getNo());
			cusDto.setFtContactWay(String.valueOf(ftContactWay));
			cusDto.setFtContactContent("渠道转客");
			cusDto.setFtContactTime(dto.getCreateTime());
		}
		cusDto.setRecommendedChannelId(dto.getRecommendedChannelId());
		resCus = customerServiceFacade.save(cusDto);
		if(!resCus.isSuccess()){
			resCus.setSuccess(false);
			resCus.setErrorCode("9999");
			resCus.setResultMessage("保存客户信息失败");
		}
		return resCus;
	}
	
	//保存分配记录
	public Response<DistributionDto> saveDistribution(CallCustomer dto, CustomerDto customer, String customerId, User user){
		DistributionDto disDto = new DistributionDto();
		disDto.setCustomerId(customer.getId());
		disDto.setProjectId(customer.getProjectId());
		disDto.setProjectCode(customer.getProjectCode());
		disDto.setUserCode(customer.getUserCode()); 
		disDto.setAssignPerson(customerId); //新归属人
		disDto.setAccessCode(customer.getAccessCode());
		disDto.setMerchantId(customer.getMerchantId());
		disDto.setDistributionTime(DateUtils.getCurrentTS());
		disDto.setIsValid("1"); //有效
		disDto.setCreateUserId(user.getId()); //分配人
		disDto.setProcessStatus(ProcessStatusEnum.YES.getNo());
		disDto.setDelFlag("0");
		Response<DistributionDto> resDis = distributionServiceFacade.save(disDto);
		
		return resDis;
	}
	
	//保存跟进记录
	public Response<FollowDto> saveFollow(CallCustomer dto, CustomerDto customer, String customerId, User user){
		//查询电话沟通记录
		List<TelRecordDto> telList = new ArrayList();
		TelRecordDto telDto = new TelRecordDto();
		telDto.setRelationId(dto.getId());
		telDto.setRelationType("1");
		telDto.addDesc("create_time");
		ResponseList<TelRecordDto> res = callCustomerServiceFacade.getTelRecordList(telDto);
		if(res.isSuccess()){
			if(res.getEntity() != null){
				dto.setLastCallTime(res.getEntity().get(0).getUpdateTime()); //最后沟通时间
				telList = res.getEntity();
			}
		}
		
		//跟进内容,当来源为call客时拼接内容
		StringBuffer content = new StringBuffer();
		if(!"2".equals(dto.getSource())){
			content.append("关注问题：" + (dto.getConcern()==null?"":dto.getConcern()));		
			content.append("<br/>备注：" + (dto.getRemark()==null?"":dto.getRemark()));
			content.append("<br/>到访时间： " + (dto.getVisitTime()==null?"":DateUtils.DateToString(dto.getVisitTime(), DateStyle.YYYY_MM_DD)));
		}
		
		//查询跟进人userCode,当维护人为空时，设置操作人为归属人
		Long maintainUser = dto.getMaintainUser();
		if(maintainUser == null){
			maintainUser = Long.parseLong(customerId);
		}
		Response<User> resUser =  userServiceFacade.findById(maintainUser);
		
		//保存跟进总记录
		FollowDto fd = new FollowDto();
	 	fd.setMerchantId(customer.getMerchantId());
	 	if(resUser.getEntity() != null){
	 		fd.setUserCode(resUser.getEntity().getUserCode());
	 	}
	 	fd.setCreateUserId(user.getId());
	 	fd.setCustomerId(customer.getId());
	 	fd.setProjectId(customer.getProjectId());
	 	fd.setProjectCode(customer.getProjectCode());
	 	fd.setAccessCode(customer.getProjectCode());
	 	fd.setDelFlag("0");
		fd.setFollowContent(content.toString());
		fd.setFollowType(FollowTypeEnum.TEXT.getNo());
		fd.setFollowTime(customer.getCreateTime());
		fd.setFollowMode(FollowModeEnum.GOCALL.getNo());
		fd.setUpdateTime(customer.getCreateTime());
		fd.setIsRead(IsReadEnum.UNREAD.getNo());
		fd.setIsSend("0");
	 	Response<FollowDto> resFollow = followServiceFacade.save(fd);
		
		//保存跟进明细记录
		for(int i = 0; i < telList.size(); i++){
			TelRecordDto tel = (TelRecordDto)telList.get(i);
			fd.setTelRecordId(tel.getId());
			fd.setDelFlag("0");
			fd.setFollowContent("拨打电话自动生成跟进");
			fd.setFollowType(FollowTypeEnum.VOICE.getNo());
			fd.setFollowTime(tel.getCreateTime());
			fd.setFollowMode(FollowModeEnum.GOCALL.getNo());
			fd.setUpdateTime(tel.getCreateTime());
			fd.setIsRead(IsReadEnum.UNREAD.getNo());
			fd.setIsSend("0");
			Response<FollowDto> resDto = followServiceFacade.save(fd);
		}
		return resFollow;
	}
}
